
$(document).ready(function() 
{
	$('#city_id').autocomplete({
    	serviceUrl: '/reference/geo/complete',
 	    minChars: 2,
 	    delimiter: /(,|;)\s*/, // regex or character
 	    maxHeight: 400,
 	    width: 300,
 	    zIndex:  9999,
 	    deferRequestBy: 300, //miliseconds
 	    params: { level: 3},
 	    noCache: false,
 	    onSelect: function(value, data){
 	    	$("#city_id_hidden").val(data);
 	    }    	
    });
	
    $('#daterange').daterangepicker({
    	dateFormat: 'd.mm.yy',
    	presetRanges: [
			{
				text: 'Ближайший месяц', 
				dateStart: 'today', 
				dateEnd: 'today+1month' 
			},
			{
				text: 'Ближайшие выходные', 
				dateStart: 'next saturday', 
				dateEnd: 'next sunday' 
			},
			{
				text: 'Следующие выходные', 
				dateStart: Date.today().add(1).week().moveToDayOfWeek(6).toString('d.MM.yy'),
				dateEnd: Date.today().add(1).week().moveToDayOfWeek(0).toString('d.MM.yy')
			},
			{
				text: 'Новогодние каникулы', 
				dateStart: function(){ 
					var a = Date.today(); 
					a.setMonth(11); 
					a.setDate(29);
					return a;
				},
				dateEnd: function(){ 
					var a = Date.today().add(1).year(); 
					a.setMonth(0); 
					a.setDate(10); 
					return a; 
				}
			}
		],
		presets: {
			dateRange: 'Точные даты'
		}
    });
    
    
    $('#budget-0').click(function(){
    	$('#budget-element').find('.slider').remove();
    	$('#budget-element').find('.amount').remove();
    	$('#budget-type-element').addClass('hidden');
    });
    
    if ( $('#budget-1:checked').length ) {
    	v0 = $('#budget-range-start').val();
    	v1 = $('#budget-range-stop').val();
    	 setBudgetSlider(null, [v0/10, v1/10]);
    }
    
    $('#budget-1').click(setBudgetSlider);
    
    function setBudgetSlider(event, values) {
    	
    	if ( $('#budget-element').find('.slider').length ) return;
    	$('#budget-type-element').removeClass('hidden');
    	$('#budget-type-element').find('input').removeClass('hidden');
    	
    	if ( values == null ) values =  [100, 5000];
    	$('#budget-element').append($('<div class="amount"><span>Диапазон: </span><span class="display"></div></div>'));
    	$('#budget-element').append($('<div class="slider" style="width: 200px"></div>'));
    	$('#budget-element').find('.slider')
    		.slider({
    			range: true,
    			min: 1,
    			max: 10000,
    			step: 100,
    			values: values,
    			slide: function( event, ui ) {
    				$('#budget-element .amount .display').html( 'от '+(ui.values[ 0 ]*10) + ' руб.' + " до " + (ui.values[ 1 ]*10) + ' руб.' );
    				$('#budget-range-start').val(ui.values[0]*10);
    				$('#budget-range-stop').val(ui.values[1]*10);
    			}
    		});
    	element = $('#budget-element').find('.slider');
    	$('#budget-element .amount .display').html( 
        		'от '+
        		(element.slider('values', 0)*10) + ' руб' +
    			' до ' + 
    			(element.slider('values', 1)*10) + ' руб'
        );
    	
    	 $('#budget-range-start').val((element.slider('values', 0)*10));
    	 $('#budget-range-stop').val((element.slider('values', 1)*10));
    };
    
    $('#days-0').click(function(){
    	$('#days-element').find('.slider').remove();
    	$('#days-element').find('.amount').remove();
    });
    
    if ( $('#days-1:checked').length ) {
    	value = $('#days_choosed').val();
    	setDaysSlider(null, value);
    }
    
    $('#days-1').click(setDaysSlider);
    
    function setDaysSlider(event, value) {
    	if ( $('#days-element').find('.slider').length ) return;
    	if ( value == null ) value = 2;
    	$('#days-element').append($('<div class="amount"><span>Выбрано: </span><span class="display"></div></div>'));
    	$('#days-element').append($('<div class="slider" style="width: 200px"></div>'));
    	$('#days-element').find('.slider')
    		.slider({
    			min: 1,
    			max: 30,
    			step: 1,
    			value: value,
    			slide: function( event, ui ) {
    				$('#days-element .amount .display').html( (ui.value) + ' дней');
    				$('#days_choosed').val(ui.value);
    			}
    		});
    	element = $('#days-element').find('.slider');
    	$('#days-element .amount .display').html( element.slider('value') + ' дней' );
    	$('#days-choosed').val(element.slider('value'));
    };
   
    $('#tender-begin input').blur(function(){
    	var elem_id = $(this).parent().prev().find('label').attr('for');
    	setTimeout(function(){doValidation(elem_id);}, 500);
    });
    
    if ( $('#city_id_hidden').parent().find('.errors').length ) {
    	$('#city_id_hidden').parent().find('.errors').clone().appendTo( $('#city_id').parent() );
    	$('#city_id_hidden').parent().find('.errors').remove();
    }
});

function doValidation(id)
{
	url = '/tender/begin/validate';
	var data = {};

	$('#tender-begin input').each(function(){
		if( $(this).get(0).tagName == 'select') {
			id = $(this).attr('id');
			data[$(this).attr('name')] = $('#'+id+' :selected').val();
		} else {
			data[$(this).attr('name')] = $(this).val();
		}
	});

	$('#'+id).parent().find('.errors').remove();
	
	$.post(url, data, function(response){
		if( response[id] ) {
			$('#'+id).parent().append(getErrorHtml(response[id], id));
		}
	}, 'json');
}

function getErrorHtml(formErrors, id)
{
	var o = '<ul id="errors-'+id+'" class="errors">';
	for( errorKey in formErrors)
	{
		o += '<li>' + formErrors[errorKey] + '</li>';
	}
	o += '</ul>';
	return o;
}